/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
/* eslint-disable react/jsx-no-bind */
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { Form, Radio, Row, Table, Col, Button, Select, Spin, message } from 'antd';
import { Axis, Chart, Geom, Tooltip } from 'bizcharts';
import { connect } from 'dva';
import React, { PureComponent } from 'react';
import router from 'umi/router';
import InfoCheck from '@/components/InfoCheck';
import Exception from '@/components/Exception';
import { debounce } from 'lodash';
import DispatchPianqu from '@/components/_pages/Post/Area/DispatchPianqu';
import { getLStorage, saveCookie } from '@/utils/utils';
import styles from './style.less';

const reqParams = (arr = []) => {
  const addressArr = arr
    .map((val, index) => ({
      branch_id: val,
      branch_level: index + 1,
    }))
    .filter(i => i.branch_id !== 'all');
  const addressObj = addressArr[addressArr.length - 1] || {
    branch_id: 0,
    branch_level: 0,
  };
  return addressObj;
};

const FormItem = Form.Item;
const { Option } = Select;
@connect(({ allocation, loading, setting, user }) => ({
  currentUser: user.currentUser,
  allocation,
  options: setting.options,
  getAllView: loading.effects['allocation/getAllView'],
  getChartsView: loading.effects['allocation/getChartsView'],
  provinceListLoading: loading.effects['allocation/getProvinceList'],
}))
@Form.create()
export default class OverView extends PureComponent {
  constructor(props) {
    super(props);
    const {
      user_info: { phone },
    } = this.props.currentUser || {};
    this.state = {
      initArea: ['all', 'all', 'all'],
      areaData: {
        branch_id: 0,
        branch_level: 0,
      },
      area_id: getLStorage(`KB_GP_AREA_${phone}`),
    };
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/save',
      payload: {
        provinceList: [],
        cityList: [],
        addressList: [],
      },
    });
  }

  onSearch = debounce(
    () => {
      const {
        dispatch,
        form: { validateFields },
      } = this.props;
      validateFields((err, values) => {
        if (err) return;
        dispatch({
          type: 'allocation/save',
          payload: {
            search: true,
          },
        });
        const { province, city, address } = values;
        const addressObj = reqParams([province, city, address]);

        this.getData(addressObj);
        this.setState({
          areaData: addressObj,
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  getDeductionInfo() {
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/getUserInfo',
    });
  }

  // 跳转查询
  scanningQuery = (render, type = 1) => {
    if (type == 1) {
      router.push({
        pathname: '/Allocation/GunScanRecord',
        hash: '#arrive',
        query: {
          brand: render,
          send_status: '2',
        },
      });
    } else if (type == 2) {
      router.push({
        pathname: '/Allocation/GunScanRecord',
        hash: '#delivery',
        query: {
          brand: render,
          send_status: '2',
        },
      });
    } else if (type == 3) {
      router.push({
        pathname: '/Allocation/GunScanRecord',
        hash: '#sign',
        query: {
          brand: render,
          send_status: '2',
        },
      });
    }
  };

  // 获取数据
  getData = (areaData = {}) => {
    const {
      dispatch,
      allocation: { tabAllType = '0' },
      options: { key },
      currentUser = {},
    } = this.props;
    const { user_info = {} } = currentUser;
    const { branchLevel } = user_info;
    this.setState({ areaData });
    const time = (key === 'post' || key == 'yjy') && branchLevel != 3 ? '1' : tabAllType; // 驿加易、中邮除县级账号，其余无法查询今日数据
    dispatch({
      type: 'allocation/save',
      payload: {
        tabAllType: '0',
        tabArriveType: 'all',
        tabSendType: 'all',
        tabSignType: 'all',
      },
    });

    dispatch({
      type: 'allocation/getAllView',
      payload: {
        brand: 'all',
        time,
        ...areaData,
      },
    });

    dispatch({
      type: 'allocation/getChartsView',
      payload: {
        brand: 'all',
        waybill_type: 5,
        time: 30,
        ...areaData,
      },
    });

    dispatch({
      type: 'allocation/getChartsView',
      payload: {
        brand: 'all',
        waybill_type: 2,
        time: 30,
        ...areaData,
      },
    });

    dispatch({
      type: 'allocation/getChartsView',
      payload: {
        brand: 'all',
        waybill_type: 3,
        time: 30,
        ...areaData,
      },
    });
  };

  onProvinceDropdownVisibleChange = visible => {
    const { dispatch } = this.props;
    visible &&
      dispatch({
        type: 'allocation/getProvinceList',
        payload: {
          branch_id: 0,
        },
      });
  };

  handleProvinceChange = value => {
    const { dispatch, form } = this.props;
    const { setFieldsValue } = form;
    setFieldsValue({
      city: 'all',
      address: 'all',
    });
    dispatch({
      type: 'allocation/save',
      payload: {
        cityList: [],
        addressList: [],
      },
    });
    if (value == 'all') {
      return;
    }
    dispatch({
      type: 'allocation/getCityList',
      payload: {
        id: value,
      },
    });
  };

  handleCityChange = value => {
    const { dispatch, form } = this.props;
    const { setFieldsValue } = form;
    setFieldsValue({
      address: 'all',
    });
    dispatch({
      type: 'allocation/save',
      payload: {
        addressList: [],
      },
    });
    if (value === 'all') {
      return;
    }
    dispatch({
      type: 'allocation/getAddressList',
      payload: {
        id: value,
      },
    });
  };

  setAreaData = () => {
    const { currentUser = {}, dispatch } = this.props;
    const { user_info = {} } = currentUser;
    const { branchLevel, branch } = user_info;
    const arr = ['all', 'all', 'all'];
    let initArea = [];
    if (branchLevel != 0) {
      initArea = branch
        .filter(val => val.level > 0)
        .map(i => i.id)
        .concat(arr.splice(branchLevel, 3 - branchLevel));
      this.setState({
        initArea,
      });
    }
    if (branchLevel >= 1) {
      this.onProvinceDropdownVisibleChange(true);
      dispatch({
        type: 'allocation/getCityList',
        payload: {
          id: initArea[0],
        },
      });
      initArea[1] !== 'all' &&
        dispatch({
          type: 'allocation/getAddressList',
          payload: {
            id: initArea[1],
          },
        });
    }
    const addressObj = reqParams(initArea);

    this.getData(addressObj);
  };

  handleInfoReady(data) {
    if (!data.name) {
      message.warn('公司信息未完善！');
      return;
    }
    const {
      currentUser = {},
      options: { key },
    } = this.props;
    const { user_info = {} } = currentUser;
    const { branchLevel, branchId, gp_area_ids = [], area_ids } = user_info;
    const { area_id } = this.state;
    const isCompany = area_ids == '*';

    if (key == 'post' || key == 'yjy') {
      this.setState({
        isZyAccount: key == 'post' || key == 'yjy',
        isProvince: branchLevel == '1',
        isCity: branchLevel == '2',
        isCountry: branchLevel == '3',
      });
      if (branchLevel == '3') {
        // 县级账号直接查询
        this.getDeductionInfo();
        this.getData({
          branch_id: branchId,
          branch_level: branchLevel,
        });
        return;
      }
      this.setAreaData();
    } else {
      this.getData({
        area_id: gp_area_ids.includes(area_id) ? area_id : isCompany ? '0' : gp_area_ids[0],
      });
    }
  }

  // 总览，到派件趋势图到Tab
  tabsAllChange(e, type) {
    const { areaData = {} } = this.state;
    const { dispatch } = this.props;

    // 防止Tab切换请求数据
    dispatch({
      type: 'allocation/save',
      payload: {
        search: false,
      },
    });

    if (type == 'all') {
      dispatch({
        type: 'allocation/save',
        payload: {
          allViewData: [],
        },
      });
      dispatch({
        type: 'allocation/getAllView',
        payload: {
          brand: 'all',
          time: e.target.value,
          ...areaData,
        },
      });
    }
    if (type == 'arrive') {
      dispatch({
        type: 'allocation/getChartsView',
        payload: {
          brand: e.target.value,
          waybill_type: 5,
          time: 30,
          search: false,
          ...areaData,
        },
      });
    }
    if (type == 'send') {
      dispatch({
        type: 'allocation/getChartsView',
        payload: {
          brand: e.target.value,
          waybill_type: 2,
          time: 30,
          search: false,
          ...areaData,
        },
      });
    }
    if (type == 'sign') {
      dispatch({
        type: 'allocation/getChartsView',
        payload: {
          brand: e.target.value,
          waybill_type: 3,
          time: 30,
          search: false,
          ...areaData,
        },
      });
    }
  }

  // 返回趋势图模版
  bizcharts(type) {
    const cols = {
      value: {
        min: 0,
      },
    };
    const {
      allocation: {
        arriveData = [],
        sendData = [],
        signData = [],
        tabArriveType = 'all',
        tabSendType = 'all',
        tabSignType = 'all',
      },
      currentUser: { user_info = {} },
    } = this.props;
    const { realAccount } = user_info;
    const fakeAccount = realAccount == 2;

    return (
      <div>
        <div
          className="bizchartsTitle"
          style={{ padding: type == 'arrive' ? '20px 0 0 20px' : '0 0 0 20px' }}
        >
          {`近30日${type == 'arrive' ? '到' : type == 'send' ? '派' : '签收'}件数量趋势`}
        </div>
        <Radio.Group
          value={type == 'arrive' ? tabArriveType : type == 'send' ? tabSendType : tabSignType}
          onChange={e => this.tabsAllChange(e, type)}
          style={{ margin: '10px 20px', display: 'inherit', textAlign: 'left' }}
        >
          <Radio.Button value="all">全部</Radio.Button>
          <Radio.Button value="zt">中通</Radio.Button>
          {!fakeAccount && <Radio.Button value="yd">韵达</Radio.Button>}
          <Radio.Button value="sto">申通</Radio.Button>
          {!fakeAccount && <Radio.Button value="yt">圆通</Radio.Button>}
          <Radio.Button value="jt">极兔</Radio.Button>
          <Radio.Button value="ems">邮政</Radio.Button>
        </Radio.Group>
        <div style={{ height: 260 }}>
          {bizchartsTemplate(type == 'arrive' ? arriveData : type == 'send' ? sendData : signData)}
        </div>
      </div>
    );
    // 通过数据返回趋势图，没有就返回空table
    function bizchartsTemplate(data) {
      if (data.length == 0) {
        return <Table dataSource={data} />;
      }
      return (
        <Chart height={260} data={data} scale={cols} forceFit>
          <Axis name="数量" />
          <Axis name="日期" />
          <Tooltip
            containerTpl="<div class=&quot;g2-tooltip&quot;><p class=&quot;g2-tooltip-title&quot;></p><table class=&quot;g2-tooltip-list&quot;></table></div>"
            itemTpl="<tr class=&quot;g2-tooltip-list-item&quot;><td style=&quot;color:{red}&quot;>数量</td><td>{value}</td></tr>"
            offset={50}
            g2-tooltip={{
              position: 'absolute',
              visibility: 'hidden',
              border: '1px solid #efefef',
              backgroundColor: 'white',
              color: '#000',
              opacity: '0.8',
              padding: '5px 15px',
              transition: 'top 200ms,left 200ms',
            }}
            g2-tooltip-list={{
              margin: '10px',
            }}
          />
          <Geom type="line" position="dt*nbs" size={2} />
          <Geom
            type="point"
            position="dt*nbs"
            size={4}
            shape="circle"
            style={{ stroke: '#fff', lineWidth: 1 }}
          />
        </Chart>
      );
    }
  }

  onChangePianqu = area_id => {
    const { dispatch } = this.props;
    saveCookie('canGetTodayAllView', false, 0);
    dispatch({
      type: 'allocation/save',
      payload: {
        search: true,
      },
    });
    this.getData({ area_id });
  };

  render() {
    const {
      getAllView,
      allocation: {
        allViewData,
        tabAllType,
        provinceList,
        cityList,
        addressList,
        deductionInfo: { is_gp },
      },
      form: { getFieldDecorator },
      provinceListLoading,
      options: { topAccountTitle, key },
      currentUser: { user_info = {} },
    } = this.props;
    const { realAccount } = user_info;
    const fakeAccount = realAccount == 2;
    const { isProvince, isCity, isCountry, isZyAccount, initArea } = this.state;
    const province = initArea[0];
    const city = initArea[1];
    let columns = [
      {
        title: '',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '合计',
        dataIndex: 'all',
        key: 'all',
        render: (text, order) => {
          if (!isCountry && isZyAccount) return text;
          return (
            <div>
              {(order.id * 1) % 2 != 0 && tabAllType == 0 ? (
                <a
                  style={{ color: 'red' }}
                  onClick={() =>
                    this.scanningQuery(
                      'all',
                      `${order.title == '到件未推送' ? 1 : order.title == '派件未推送' ? 2 : 3}`,
                    )
                  }
                >
                  {text}
                </a>
              ) : (
                <span>{text}</span>
              )}
            </div>
          );
        },
      },
      {
        title: '韵达',
        dataIndex: 'yd',
        key: 'yd',
        render: (text, order) => {
          if (!isCountry && isZyAccount) return text;
          return (
            <div>
              {(order.id * 1) % 2 != 0 && tabAllType == 0 ? (
                <a
                  style={{ color: 'red' }}
                  onClick={() =>
                    this.scanningQuery(
                      'yd',
                      `${order.title == '到件未推送' ? 1 : order.title == '派件未推送' ? 2 : 3}`,
                    )
                  }
                >
                  {text}
                </a>
              ) : (
                <span>{text}</span>
              )}
            </div>
          );
        },
      },
      {
        title: '申通',
        dataIndex: 'sto',
        key: 'sto',
        render: (text, order) => {
          if (!isCountry && isZyAccount) return text;
          return (
            <div>
              {(order.id * 1) % 2 != 0 && tabAllType == 0 ? (
                <a
                  style={{ color: 'red' }}
                  onClick={() =>
                    this.scanningQuery(
                      'sto',
                      `${order.title == '到件未推送' ? 1 : order.title == '派件未推送' ? 2 : 3}`,
                    )
                  }
                >
                  {text}
                </a>
              ) : (
                <span>{text}</span>
              )}
            </div>
          );
        },
      },
      {
        title: '中通',
        dataIndex: 'zt',
        key: 'zt',
        render: (text, order) => {
          if (!isCountry && isZyAccount) return text;
          return (
            <div>
              {(order.id * 1) % 2 != 0 && tabAllType == 0 ? (
                <a
                  style={{ color: 'red' }}
                  onClick={() =>
                    this.scanningQuery(
                      'zt',
                      `${order.title == '到件未推送' ? 1 : order.title == '派件未推送' ? 2 : 3}`,
                    )
                  }
                >
                  {text}
                </a>
              ) : (
                <span>{text}</span>
              )}
            </div>
          );
        },
      },
      {
        title: '圆通',
        dataIndex: 'yt',
        key: 'yt',
        render: (text, order) => {
          if (!isCountry && isZyAccount) return text;
          return (
            <div>
              {(order.id * 1) % 2 != 0 && tabAllType == 0 ? (
                <a
                  style={{ color: 'red' }}
                  onClick={() =>
                    this.scanningQuery(
                      'yt',
                      `${order.title == '到件未推送' ? 1 : order.title == '派件未推送' ? 2 : 3}`,
                    )
                  }
                >
                  {text}
                </a>
              ) : (
                <span>{text}</span>
              )}
            </div>
          );
        },
      },
      {
        title: '极兔',
        dataIndex: 'jt',
        key: 'jt',
        render: (text, order) => {
          if (!isCountry && isZyAccount) return text;
          return (
            <div>
              {(order.id * 1) % 2 != 0 && tabAllType == 0 ? (
                <a
                  style={{ color: 'red' }}
                  onClick={() =>
                    this.scanningQuery(
                      'jt',
                      `${order.title == '到件未推送' ? 1 : order.title == '派件未推送' ? 2 : 3}`,
                    )
                  }
                >
                  {text}
                </a>
              ) : (
                <span>{text}</span>
              )}
            </div>
          );
        },
      },
      {
        title: '邮政',
        dataIndex: 'ems',
        key: 'ems',
        render: (text, order) => {
          if (!isCountry && isZyAccount) return text;
          return (
            <div>
              {(order.id * 1) % 2 != 0 && tabAllType == 0 ? (
                <a
                  style={{ color: 'red' }}
                  onClick={() =>
                    this.scanningQuery(
                      'ems',
                      `${order.title == '到件未推送' ? 1 : order.title == '派件未推送' ? 2 : 3}`,
                    )
                  }
                >
                  {text}
                </a>
              ) : (
                <span>{text}</span>
              )}
            </div>
          );
        },
      },
    ];
    // 假账号过滤
    if (fakeAccount) {
      columns = columns.filter(v => !['yd', 'yt'].includes(v.key));
    }

    if (is_gp == 0 && isZyAccount && isCountry) {
      // 当县级网点无共配权限时，提示
      return (
        <Exception
          type="403"
          title={`您所在的网点尚未开通共配服务，请联系${topAccountTitle}开通！`}
        />
      );
    }

    return (
      <PageHeaderLayout
        title={
          <Row type="flex" justify="space-between">
            <Col>共配数据总览</Col>
            <Col>
              {isZyAccount && !isCountry ? (
                <Form layout="inline">
                  <FormItem>
                    {getFieldDecorator('province', {
                      initialValue: province,
                    })(
                      <Select
                        disabled={isProvince || isCity || isCountry}
                        style={{ width: 150 }}
                        onDropdownVisibleChange={this.onProvinceDropdownVisibleChange}
                        onChange={this.handleProvinceChange}
                      >
                        <Option key="all" value="all">
                          全部省级
                        </Option>
                        {provinceListLoading ? (
                          <Option disabled value="loadig">
                            <Spin />
                          </Option>
                        ) : (
                          provinceList.map(val => (
                            <Option key={val.id} value={val.id}>
                              {val.name}
                            </Option>
                          ))
                        )}
                      </Select>,
                    )}
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('city', {
                      initialValue: city,
                    })(
                      <Select
                        style={{ width: 150 }}
                        onChange={this.handleCityChange}
                        disabled={isCity || isCountry}
                      >
                        <Option key="all" value="all">
                          全部市级
                        </Option>
                        {cityList.map(val => (
                          <Option key={val.id} value={val.id}>
                            {val.name}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </FormItem>
                  <FormItem>
                    {getFieldDecorator('address', {
                      initialValue: 'all',
                    })(
                      <Select style={{ width: 150 }} disabled={isCountry}>
                        <Option key="all" value="all">
                          全部县级
                        </Option>
                        {addressList.map(val => (
                          <Option key={val.id} value={val.id}>
                            {val.name}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </FormItem>
                  <FormItem>
                    <Button onClick={this.onSearch} type="primary">
                      查询
                    </Button>
                  </FormItem>
                </Form>
              ) : null}
              {key == 'yz' ? <DispatchPianqu type="gp" onChange={this.onChangePianqu} /> : null}
            </Col>
          </Row>
        }
      >
        <InfoCheck onReady={this.handleInfoReady.bind(this)} />
        <div className={styles.main}>
          <div className={styles.overView}>
            <div className="content">
              <Row style={{ marginBottom: '20px' }}>
                <Radio.Group
                  value={tabAllType}
                  onChange={e => this.tabsAllChange(e, 'all')}
                  style={{ margin: '0 0  10px 10px', display: 'inherit', textAlign: 'left' }}
                >
                  {(!isZyAccount || isCountry) && <Radio.Button value="0">今日</Radio.Button>}
                  <Radio.Button value="1">昨天</Radio.Button>
                  <Radio.Button value="7">前7天</Radio.Button>
                  <Radio.Button value="30">前30天</Radio.Button>
                </Radio.Group>
                <Table
                  className="table"
                  dataSource={allViewData}
                  columns={columns}
                  pagination={false}
                  rowKey="id"
                  loading={getAllView}
                />
              </Row>
              <Row>{this.bizcharts('arrive')}</Row>
              <Row>{this.bizcharts('send')}</Row>
              <Row>{this.bizcharts('sign')}</Row>
            </div>
          </div>
        </div>
      </PageHeaderLayout>
    );
  }
}
